package com.qf.courtesycard.user.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.qf.courtesyard.domain.vo.ResultVo;
import com.qf.courtesycard.user.entity.User;
import com.qf.courtesycard.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lx
 * @since 2023-03-10
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 生成token
     *
     * @param name
     * @param phoneNum
     * @return
     * @throws Exception
     */
    @RequestMapping("/getToken")
    @HystrixCommand(fallbackMethod = "fallback",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "30000")
            },
            threadPoolKey = "ticketpool",
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "5"),
                    @HystrixProperty(name = "maxQueueSize", value = "5")
            })
    public ResultVo getToken(@RequestParam("name") String name, @RequestParam("phoneNum") String phoneNum) throws Exception {
        log.debug("接收到的参数为name={},phoneNum={}", name, phoneNum);
        String token = userService.checkToken(name, phoneNum);
        ResultVo result = ResultVo.ok();
        result.put("data", token);
        return result;
    }

    /**
     * 根据手机号查询用户信息
     * 为抢票模块调用
     *
     * @param phoneNum
     * @return
     */
    @RequestMapping("/getUser")
    public ResultVo getUser(String phoneNum) {
        log.debug("接受到的参数phoneNum={}", phoneNum);
        User user = userService.getUser(phoneNum);
        ResultVo ok = ResultVo.ok();
        ok.put("data", user);
        return ok;
    }

    public ResultVo fallback(@RequestParam("name") String name, @RequestParam("phoneNum") String phoneNum) {
        System.out.println(name + ":" + phoneNum + ",没有获取token");
        ResultVo ok = ResultVo.ok();
        ok.put("data", null);
        return ok;
    }
}
